package com.fan.txl.ui;

import android.app.Dialog;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.base.txl.utils.ComponentUtils;
import com.elvishew.xlog.XLog;
import com.fan.txl.R;
import com.fan.txl.data.base.RspList;
import com.fan.txl.data.feed.Feed;
import com.fan.txl.listener.OnClick;
import com.fan.txl.databinding.ActivityFriendsBinding;
import com.fan.txl.mock.api.service.FeedsService;
import com.fan.txl.ui.adapter.BindAdapt;
import com.fan.txl.ui.adapter.FeedBindAdapt;
import com.fan.txl.ui.base.BaseActivity;
import com.fan.txl.ui.routers.ComponentRouters;
import com.fan.txl.utils.RecyclerViewUtils;
import com.github.mzule.activityrouter.annotation.Router;
import com.jakewharton.rxbinding2.view.RxView;
import com.trello.rxlifecycle2.android.ActivityEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.base.txl.utils.RxUtils;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;


@Router({ComponentRouters.domain+ComponentRouters.feeds,ComponentRouters.feeds})
public class FeedsUI extends BaseActivity implements OnClick,SwipeRefreshLayout.OnRefreshListener {


    BindAdapt<Feed> mAdapt;
    List<Feed> mFriends = new LinkedList<>();
    Dialog dialog;


    SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    public boolean onSearchRequested() {
        return super.onSearchRequested();
    }

    @Override
    public boolean onSearchRequested(SearchEvent searchEvent) {
        return super.onSearchRequested(searchEvent);
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityFriendsBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_friends);
        binding.setFriendsEvent(this);
        binding.setLoading(mLoading);
        dialog = new Dialog(this);
        dialog.setContentView(R.layout.loading_up);


        setSupportActionBar(binding.toolbar);
        //歌曲模式
        binding.toolbar.setTitle("任贤齐");
        binding.toolbar.setSubtitle("伤心太平洋");

        mSwipeRefreshLayout=binding.swipeRefreshLayout;
        mSwipeRefreshLayout.setOnRefreshListener(this);

        mAdapt= new FeedBindAdapt(mFriends);
        binding.friends.setLayoutManager(RecyclerViewUtils.getHLayMgr(this));
        binding.friends.setAdapter(mAdapt); //adapt.notifyItemInserted(),adapt.notifyItemRemoved(),adapt.notifyItemChanged() //friends.setOnFlingListener();
        handleIntent(getIntent());
        mockFeedsService();

        RxView.clicks(binding.fab)
                .throttleFirst(300, TimeUnit.MILLISECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        ComponentUtils.start(FeedsUI.this,ComponentRouters.design);
                    }
                });

       /* PushMsg pushMsg= new PushMsg();
            pushMsg.setTitle("零钱啦");
            pushMsg.setText("####我们开始发钱啦，你来不来？");
        pushMsg.setDate(new Date());
        Realm realm= Realm.getDefaultInstance();
        RealmResults<PushMsg> results = realm.where(PushMsg.class).findAll();*/

       // int size=results.size();
        //String text=results.get(0).getTitle();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }


    private void handleIntent(Intent intent){
        if (Intent.ACTION_SEARCH.equals(intent.getAction())){
           /* String query = intent.getStringExtra(SearchManager.QUERY);
            if (!"15108280907".equalsIgnoreCase(query)){
                return;
            }
            Feed feed  = new Feed();
            feed.setFeedUserName("1544578524");
            feed.setFeedUserName("王大");
            feed.setUserName("1544578524");
            feed.setUserName("王菲");
            feed.setFeed("我是你的心情");
            mAdapt.getData().clear();
            mAdapt.getData().add(feed);
            mAdapt.notifyDataSetChanged();*/
        }
    }

    public void mockFeedsService(){
         getAPIService()
                 .getRpcService()
        .rpc(FeedsService.methodSearch,FeedsService.service,FeedsService.requestSearch)
                .compose(RxUtils.<String>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
                .compose(this.<String>bindUntilEvent(ActivityEvent.STOP))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        onShow();
                    }
                })
                .doOnTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        onHide();
                        hideLoading();
                    }
                })
               .doOnNext(new Consumer<String>() {
                   @Override
                   public void accept(String listRsp) throws Exception {
                    //可以处理返回来的数据
                   }
               })
                 .flatMap(new Function<String, Observable<LinkedList<Feed>>>() {
                     @Override
                     public Observable<LinkedList<Feed>> apply(String s) throws Exception {
                         XLog.d(s);
                         RspList<Feed> rsp=  JSON.parseObject(s,new TypeReference<RspList<Feed>>(){});
                         return Observable.just(rsp.data);
                     }
                 })
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<LinkedList<Feed>>() {
                    @Override
                    public void onNext(LinkedList<Feed> feeds) {
                        //userView.setUser(user);
                        mAdapt.getData().addAll(feeds);
                        mAdapt.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



    private void hideLoading(){
        mSwipeRefreshLayout.setRefreshing(false);
    }



    @Override
    public void click(View view) {
        Feed feed=  mAdapt.getData().get(0);
       /* feed.setUserName("1544578524");
        feed.setUserName("王大");
        feed.setFeedUserName("1544578524");
        feed.setFeedUserName("王菲");*/
        feed.setFeed("hi,王");
        feed.setCreateTime(Calendar.getInstance().getTime());
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case  android.R.id.home:
                Toast.makeText(this, "nav", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        SearchManager searchManager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
        SearchableInfo searchableInfo= searchManager.getSearchableInfo(getComponentName());
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
        searchEditText.setTextColor(ContextCompat.getColor(this,android.R.color.white));
        searchEditText.setHintTextColor(ContextCompat.getColor(this,android.R.color.white));

        searchView.setSearchableInfo(searchableInfo);
        return true;
    }


    @Override
    public void onRefresh() {
        mockFeedsService();
    }
}
